import React, { useCallback } from "react";
import { useFormContext } from "../common/context";
import './style.css'
import { get } from "lodash";
const Field = (props) => {
    const { state, dispatch, submitAction } = useFormContext();
    const { children, title, name, rules } = props;
    const { [name]: value } = state;
    const getValue = useCallback((e) => {
        const target = get(e, 'target', {});
        if (Object.prototype.hasOwnProperty.call(target, 'value')) {
            return get(e, 'target.value');
        }
        else {
            return e;
        }
    }, [])
    const onChange = useCallback((e) => {
        const val = getValue(e);
        dispatch({
            type: 'formChange',
            payload: {
                [name]: val,
            }
        });
    }, [getValue, dispatch, name])
    return (
        <div className="field">
            <span className="fieldTitle">
                {title}
            </span>
            <div style={{ padding: '10px' }}>
                {!!children && typeof children === 'object' && !Array.isArray(children) && React.cloneElement(children, { onChange, value })}
                {!!children && typeof children === 'object' && Array.isArray(children) && <>{children}</>}
                {!!children && typeof children === 'function' && children({ onChange, value })}
                {rules.required && value === '' && submitAction && (<div style={{ marginTop: '5px', color: 'red', fontSize: '10px' }}>{rules.message}</div>)}
            </div>

        </div>
    )
}
export default React.memo(Field)